<?php


namespace App\Services;

use App\Admin\Actions\Post\TransactionPost;
use App\Extensions\Actions\Post\BookGrantPost;
use App\Extensions\Actions\Upload\CertUploadAction;
use App\Extensions\Exporters\BookApplyExporter;
use App\Models\Department;
use Carbon\Carbon;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Tab;
use Illuminate\Database\Eloquent\Builder;

class BookApplyService extends BaseApplyService
{

    public function gridColumns(Grid $grid, $role = 0): Grid
    {
        $user = Admin::user();
        $grid->model()->when(request()->get('action') == 'reviewing', function ($query) {
            return $query->where('review_status', 0);
        })->with(['department', 'user']);
        $grid->column('uuid', __('系统编号'))->modal('详情', function ($model) {
            return self::detail($model);
        });
        $grid->column('name', __('名称'));
        $grid->column('first_inventor', __('第一开发人'));
        $grid->column('applicant', __('著作权人'));
        $grid->column('department.name', __('dept_name'));
        $grid->column('cts', __('技术核心方案'))->display(function ($cts) {
            return $cts ? '查看' : '';
        })->modal('详情', function ($model) {
            return $model->cts;
        });
        $grid->column('file', '登记备案表')->display(function ($value) {
            return $value ? '下载' : '';
        })->link(function ($model) {
            return file_custom_preview_url($model['file'], '(登记备案表)' . $model['name']);
        });
        if ($mobile = config('settings.code_default_mobile')) {
            $grid->column('_mobile', __('验证码接收手机号'))->display(function () use ($mobile) {
                return $mobile;
            })->copyable();
        }
        $grid->column('cert', '著作权证书')->display(function ($value) {
            return $value ? '下载' : '';
        })->link(function ($model) {
            return file_custom_preview_url($model['cert'], '(证书)' . $model['name']);
        });
        tree_review_status($grid);
        $grid->column('user.name', '创建人');
        $grid->column('created_at', '创建时间')->display(function ($value) {
            return Carbon::parse($value)->toDateString();
        });
        $this->gridHeader($grid, $role);
        $this->gridActions($grid, $role, function (Grid\Displayers\Actions $actions, $row) use ($role, $user) {
            if ($row->review_status == 1 && !$row->status) {
                if ($role == 1 || $user['id'] == $row['user_id']) {
                    $actions->prepend(new BookGrantPost($actions));
                }
            }
        });
        $grid->hideColumns(['created_at', 'user.name']);
        return $grid;
    }

    public function gridPublishColumns(Grid $grid, $role = 0): Grid
    {
        $user = Admin::user();
        $grid->model()->with(['department', 'user'])->where('review_status', 1)->where('status', 1);
        $grid->column('uuid', __('系统编号'))->modal('详情', function ($model) {
            return self::detail($model);
        });
        $grid->column('register_no', __('登记号'));
        $grid->column('name', __('名称'));
        $grid->column('complete_date', __('完成日期'));
        $grid->column('first_inventor', __('第一开发人'));
        $grid->column('applicant', __('著作权人'));
        $grid->column('department.name', __('dept_name'));
        $grid->column('cts', __('技术核心方案'))->display(function ($cts) {
            return $cts ? '查看' : '';
        })->modal('详情', function ($model) {
            return $model->cts;
        });
        $grid->column('file', '登记备案表')->display(function ($value) {
            return $value ? '下载' : '';
        })->link(function ($model) {
            return file_custom_preview_url($model['file'], '(登记备案表)' . $model['name']);
        });
        $grid->column('cert_date', __('下证时间'));
        $grid->column('cert', '著作权证书')->display(function ($value) {
            return $value ? '下载' : '';
        })->link(function ($model) {
            return file_custom_preview_url($model['cert'], '(证书)' . $model['name']);
        });
        $grid->column('user.name', '创建人');
        $grid->column('created_at', '创建时间')->display(function ($value) {
            return Carbon::parse($value)->toDateString();
        });
        $this->gridHeader($grid, $role);
        $this->gridActions($grid, $role, function (Grid\Displayers\Actions $actions, $row) use ($role, $user) {
            if ($user->id == $row->user_id && $row->status == 1 && !$row->cert) {
                $actions->prepend(new CertUploadAction($actions));
            }
            if ($role == 1 && $row->status == 1) {
                $actions->prepend(new  TransactionPost($actions));
            }
        });
        $grid->disableCreateButton();
        $grid->hideColumns(['created_at', 'user.name']);
        return $grid;
    }

    protected function gridHeader(Grid $grid, $role = 0)
    {
        if ($role == 1) {
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->where(function ($query) {
                        $query->where('inventor', 'like', "%$this->input%");
                    }, '开发人');
                    $filter->where(function ($query) {
                        $query->whereYear('created_at', "$this->input");
                    }, '申请年份')->year();
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->equal('department_id', __('dept_name'))->select(Department::departmentOptions());
                    $filter->where(function ($query) {
                        $query->whereYear('cert_date', "$this->input");
                    }, '下证年份')->year();
                });
            });
        } else {
            $grid->batchActions(function (Grid\Tools\BatchActions $actions) {
                $actions->disableDelete();
            });
            $grid->disableFilter();
        }
        // $grid->disableExport();
        $grid->exporter(new BookApplyExporter());
        $grid->quickSearch(function ($query, $value) {
            $query->where(function (Builder $query) use ($value) {
                $query->where('name', 'like', "%$value%")
                    ->orWhere('applicant', 'like', "%$value%")
                    ->orWhere('inventor', 'like', "%$value%")
                    ->orWhere('mobile', 'like', "%$value%")
                    ->orWhere('register_no', 'like', "%$value%")
                    ->orWhereHas('department', function ($query) use ($value) {
                        $query->where('name', 'like', "%$value%");
                    });
            });
        })->placeholder('关键字');
    }

    public function formFields(Form $form, $role = 0)
    {
        $user = Admin::user();
        $form->text('name', __('拟申请软件著作权名称'))->required();
        $form->text('inventor', __('开发人姓名（全部)'))->required()->help('开发人姓名以逗号隔开')->default($user->name);
        $form->text('first_inventor', __('第一开发人'))->required()->default($user->name);
        $form->mobile('mobile', __('联系电话'))->required()->default($user->mobile);
        $form->text('applicant', __('著作权人'))->required()->default(org_name());
        $form->textarea('cts', '核心技术方案')->placeholder('核心技术方案')->required();
        $mimes = 'png,jpg,jpeg,pdf';
        $form->file('file', '登记备案表')
            ->rules('required|mimes:' . $mimes, ['required' => '请上传文件', 'mimes' => '文件类型错误'])
            ->required()
            ->uniqueName()
            ->help(sprintf('%s,%s',
                SettingService::bookFilingTemplateATag(),
                '&nbsp;上传类型：' . $mimes
            ));
        if ($mobile = config('settings.code_default_mobile')) {
            $form->display('_mobile', '验证码接收手机号')->default($mobile);
        }
    }

    public static function detail($model)
    {
        $tab = new Tab();
        $tab->add('基本信息', Admin::show($model, function (Show $show) use ($model) {
            $show->panel()->view('show.tab-panel');
            $show->field('uuid', __('编号'));
            $show->field('name', __('名称'));
            $show->field('inventor', __('开发人'));
            $show->field('first_inventor', __('第一开发人'));
            $show->field('department.name', __('dept_name'));
            $show->field('mobile', __('联系电话'));
            if ($mobile = config('settings.code_default_mobile')) {
                $show->field('_mobile', __('验证码接收手机号'))->as(function () use ($mobile) {
                    return $mobile;
                });
            }
            $show->field('file', __('登记备案表'))->as(function ($val) {
                return $val ? '下载' : '';
            })->link(file_custom_preview_url($model['file'], '(登记备案表)' . $model['name']));
            $show->field('cert', __('证书'))->as(function ($val) {
                return $val ? '下载' : '';
            })->link(file_custom_preview_url($model['cert'], '(证书)' . $model['name']));
            $show->field('register_no', __('登记号'));
            $show->field('complete_date', __('完成时间'));
            $show->field('cert_date', __('下证时间'));
            $show->field('user.name', __('创建人'));
            $show->field('created_at', __('创建时间'));
        }));
        if ($model->cts) {
            $tab->add('技术核心方案', $model->cts);
        }
        return $tab;
    }
}
